//商品页

<template>
  <div>
    <!-- 顶部状态栏 -->
    <div class="user-status-bar">
      <template v-if="isLoggedIn">
        <span class="user-info">👤 {{ username || '用户' }}</span>
        <el-button size="small" @click="handleLogout" class="logout-btn">退出登录</el-button>
      </template>
      <template v-else>
        <el-button size="small" type="primary" @click="goToLogin" class="login-btn">登录</el-button>
      </template>
    </div>
    <el-container class="product-list-container">
      <!-- 轮播图区域 -->
      <div class="carousel-section">
        <el-carousel height="340px" :interval="3500" arrow="always">
          <el-carousel-item v-for="(item, idx) in carouselImages" :key="idx">
            <div class="carousel-img-wrapper" style="cursor:pointer;position:relative;" @click="goToProductDetail(item.id)">
              <img :src="item.url" :alt="item.alt" class="carousel-img" />
              <div class="carousel-caption">{{ item.caption }}</div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>
      <el-header class="product-list-header">
        <el-row type="flex" justify="space-between" align="middle" style="width: 100%;">
          <el-col :span="12">
            <h2>商品列表</h2>
          </el-col>
          <el-col :span="12" style="text-align: right;">
            <el-button type="primary" @click="goToAddProduct">新增商品</el-button>
          </el-col>
        </el-row>
        <!-- 搜索框 -->
        <el-row style="width: 100%; margin-top: 20px;">
          <el-col :span="24">
            <el-input
              v-model="searchQuery"
              placeholder="请输入商品标题或描述进行搜索"
              clearable
              prefix-icon="Search"
            ></el-input>
          </el-col>
        </el-row>
      </el-header>
      <el-main class="product-list-main">
      <div v-if="loading" class="loading-state">
        <el-spinner size="large"></el-spinner>
        <p>加载中...</p>
      </div>
      <div v-else-if="error" class="error-state">
        <el-alert :title="error" type="error" show-icon></el-alert>
      </div>
      <el-row v-else :gutter="20" class="product-grid">
        <el-col
          v-for="product in filteredProducts" 
          :key="product.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          class="product-col"
          @click="goToProductDetail(product.id)"
          style="cursor:pointer;"
        >
          <el-card :body-style="{ padding: '0px' }" class="product-card">
            <img :src="product.picPaths" class="product-image" alt="Product Image" />
            <div style="padding: 14px;">
              <div class="product-title">{{ product.title }}</div>
              <div class="product-price">¥ {{ product.price }}</div>
              <div class="product-desc">{{ product.desc }}</div>
              <div class="product-meta">
                <span class="author-name">作者: {{ product.authorName || '匿名用户' }}</span>
                <span class="added-time">发布时间: {{ formatTime(product.addedTime) }}</span>
                <el-button type="danger" size="small" class="delete-btn" @click.stop="handleDelete(product.id)">删除</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <div v-if="filteredProducts.length === 0 && !loading && !error" class="no-products"> <!-- 修改这里 -->
        <el-empty description="暂无商品"></el-empty>
      </div>
    </el-main>
  </el-container>
  </div>
</template>


<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'; // 确保 ElMessageBox 也被导入
import { useRouter } from 'vue-router';
import { Search } from '@element-plus/icons-vue';
import { useUserStore } from '@/stores/user';
import axios from 'axios'; 

// 轮播图内容动态获取（取商品API前3条）
interface CarouselItem {
  id: number;
  url: string;
  alt: string;
  caption: string;
}
const carouselImages = ref<CarouselItem[]>([]);

const fetchCarouselImages = async () => {
  try {
    const response = await fetch('/api/demo/getallitems?typeIndex=2');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    if (Array.isArray(data)) {
      // 随机选取三条商品
      const shuffled = data.slice().sort(() => Math.random() - 0.5);
      carouselImages.value = shuffled.slice(0, 3).map((item: any) => ({
        id: item.id,
        url: item.picPaths || 'https://images.unsplash.com/photo-1519125323398-675f0ddb6308?auto=format&fit=crop&w=800&q=80',
        alt: item.title || '商品封面',
        caption: item.title || '精选商品'
      }));
    }
  } catch (e) {
    // 失败时设置默认图片
    carouselImages.value = [
      { id: 0, url: 'https://img.shetu66.com/2023/07/06/1688611155457376.png', alt: '默认', caption: '欢迎来到商品平台' }
    ];
  }
};

// 用户状态栏相关
const userStore = useUserStore();
const isLoggedIn = computed(() => userStore.isLoggedIn);
const username = computed(() => userStore.currentUsername);

const goToLogin = () => {
  router.push('/login');
};

const handleLogout = () => {
  userStore.clearUser();
  router.push('/login');
};

interface Product {
  id: number;
  title: string;
  picPaths: string;
  price: string;
  desc: string;
  addedTime: string;
  userid: number | null;
  categoryid: number | null;
  authorName: string | null;
}

const products = ref<Product[]>([]);
const loading = ref(true);
const error = ref<string | null>(null);
const searchQuery = ref(''); // 新增：搜索关键词响应式变量

const fetchProducts = async () => {
  loading.value = true;
  error.value = null;
  let loadingInstance: any;
  try {
    loadingInstance = ElLoading.service({ fullscreen: true, text: '加载商品中...' });
    const response = await fetch('/api/demo/getallitems?typeIndex=2');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    if (Array.isArray(data)) {
      products.value = data;
    } else {
      // 如果API返回的不是数组，尝试直接赋值或处理
      console.warn('API返回数据格式可能不符合预期，尝试直接赋值:', data);
      products.value = data; // 假设即使不是数组，也可能是一个包含商品的结构
    }
    ElMessage.success('商品加载成功！');
  } catch (e: any) {
    error.value = '获取商品失败: ' + e.message;
    ElMessage.error(error.value);
    console.error('获取商品失败:', e);
  } finally {
    loading.value = false;
    if (loadingInstance) {
      loadingInstance.close();
    }
  }
};

const formatTime = (timeString: string) => {
  if (!timeString) return '未知时间';
  try {
    const date = new Date(timeString);
    return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }).replace(/\//g, '-');
  } catch (e) {
    return timeString; // 如果解析失败，返回原始字符串
  }
};

onMounted(() => {
  fetchProducts();
  fetchCarouselImages();
});

const router = useRouter();

const goToAddProduct = () => {
  router.push('/add-product');
};

const goToProductDetail = (id: number) => {
  router.push(`/product-detail/${id}`);
};

// 新增：根据搜索关键词过滤商品列表的计算属性
const filteredProducts = computed(() => {
  if (!searchQuery.value) {
    return products.value;
  }
  const query = searchQuery.value.toLowerCase();
  return products.value.filter(product => {
    return (
      product.title.toLowerCase().includes(query) ||
      product.desc.toLowerCase().includes(query)
    );
  });
});
const handleDelete = async (id: number) => {
  ElMessageBox.confirm('此操作将永久删除该商品, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const response = await axios.post('/api/demo/deleteitem', {
        delid: id,
        typeIndex: 2,
      });
      // 根据API返回的字符串判断是否成功
      if (response.data === 'del ok!!!') {
        ElMessage.success('删除成功');
        fetchProducts(); // 重新加载产品列表
      } else {
        ElMessage.error(response.data || '删除失败');
      }
    } catch (error) {
      console.error('删除请求失败:', error);
      ElMessage.error('删除请求失败');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};
</script>

<style scoped>
.user-status-bar {
  width: 100%;
  background: linear-gradient(90deg, #3896fb 0%, #6a82fb 100%);
  box-shadow: 0 2px 8px rgba(56, 150, 251, 0.08);
  border-bottom: 1px solid #e3eaf5;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 0 36px 0 0;
  min-height: 52px;
  font-size: 16px;
  margin-bottom: 18px;
  border-radius: 0 0 12px 12px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}
.user-info {
  margin-right: 16px;
  color: #fff;
  font-weight: 600;
  letter-spacing: 1px;
  font-size: 17px;
  display: flex;
  align-items: center;
  text-shadow: 0 1px 2px rgba(0,0,0,0.08);
}
.login-btn, .logout-btn {
  margin-left: 8px;
  border-radius: 18px !important;
  font-size: 15px;
  font-weight: 500;
  padding: 5px 18px;
  box-shadow: 0 2px 8px rgba(106,130,251,0.08);
  transition: background 0.2s, color 0.2s;
}
.login-btn {
  background: #fff !important;
  color: #3896fb !important;
  border: 1px solid #fff !important;
}
.login-btn:hover {
  background: #eaf2ff !important;
  color: #6a82fb !important;
}
.logout-btn {
  background: rgba(255,255,255,0.15) !important;
  color: #fff !important;
  border: 1px solid #fff2 !important;
}
.logout-btn:hover {
  background: #fc5c7d !important;
  color: #fff !important;
  border: 1px solid #fc5c7d !important;
}

.carousel-section {
  margin-bottom: 30px;
}
.carousel-img-wrapper {
  position: relative;
}
.carousel-img {
  width: 100%;
  height: 260px;
  object-fit: cover;
  border-radius: 8px;
}
.carousel-caption {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.4);
  color: #fff;
  padding: 12px 0;
  text-align: center;
  font-size: 1.2em;
  border-radius: 0 0 8px 8px;
  letter-spacing: 1px;
}

.product-list-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 100px 20px 30px 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: relative;
}

.product-list-header {
  display: flex;
  flex-direction: column; /* 修改为列布局，使搜索框在标题下方 */
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.product-list-header h2 {
  color: #303133;
  font-size: 28px;
  font-weight: bold;
  margin: 0; /* 移除默认外边距 */
}

/* 移除原有的 .add-product-button 样式，因为按钮位置已通过 el-row/el-col 调整 */
/* .add-product-button {
  margin-left: 20px;
} */

.loading-state,
.error-state,
.no-products {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  color: #909399;
  font-size: 18px;
}

.product-grid {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start; /* 商品卡片左对齐 */
}

.product-col {
  margin-bottom: 20px;
}

.product-card {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.product-image {
  width: 100%;
  height: 200px; /* 固定图片高度 */
  object-fit: cover; /* 保持图片比例并裁剪 */
  display: block;
}

.product-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  font-size: 20px;
  color: #ff4949; /* 醒目的价格颜色 */
  font-weight: bold;
  margin-bottom: 10px;
}

.product-desc {
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
  height: 60px; /* 固定描述高度，防止布局跳动 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 限制描述为3行 */
  -webkit-box-orient: vertical;
  margin-bottom: 10px;
}

.product-meta {
  font-size: 12px;
  color: #909399;
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  border-top: 1px solid #ebeef5;
  padding-top: 10px;
  align-items: center;
}

.delete-btn {
  margin-left: 10px;
}

.author-name {
  font-weight: bold;
}
</style>